package io.example;

import io.example.common.utils.PropertiesUtils;
import io.example.common.utils.StringUtils;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Future;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;

/**
 * Created by Administrator on 2018/3/8.
 * 入口Verticle，在此启动各子Verticle
 */
public class MainVerticle extends AbstractVerticle {

    private static Logger logger = LoggerFactory.getLogger(MainVerticle.class);

    private static String httpServerPort;

    private static Properties jdbcProp;

    static {
        //从配置读取端口号
        PropertiesUtils hsp = new PropertiesUtils("config/httpServer.properties");
        httpServerPort = hsp.readProperty("http.server.port");
        PropertiesUtils hjp = new PropertiesUtils("config/hikariCP.jdbc.properties");
        jdbcProp = hjp.getProperties();
    }

    public void start(Future<Void> startFuture) throws Exception {
        Future<String> dataInitFuture = Future.future();
        JsonObject jdbcClientConfig = new JsonObject();
        jdbcProp.keySet().forEach(key -> {
            String value = jdbcProp.getProperty(key.toString());
            jdbcClientConfig.put(key.toString(), StringUtils.isInteger(value) ? Integer.valueOf(value) : value);
        });
        DeploymentOptions jdbcClientOptions = new DeploymentOptions().setConfig(jdbcClientConfig);
        //初始化内存数据库数据
        vertx.deployVerticle("io.example.jdbc.DataInitVerticle", jdbcClientOptions, dataInitFuture);
//        Future<String> demoDaoFuture = Future.future();
//        vertx.deployVerticle("io.example.jdbc.DemoDaoVerticle", jdbcClientOptions, demoDaoFuture);
        dataInitFuture.compose(id -> {
            //DataInitVerticle发布后执行
            Future<String> demoDaoFuture = Future.future();
            vertx.deployVerticle("io.example.jdbc.DemoDaoVerticle", jdbcClientOptions, demoDaoFuture);
            return demoDaoFuture;
        })
        .compose(id -> {
            //DemoDaoVerticle发布后执行
            Future<String> httpServerFuture = Future.future();
            //启动http服务器 设置为2个实例 可以有效利用多核服务器 根据核数量决定配置的实例数
            JsonObject httpServerConfig = new JsonObject().put("http.server.port", StringUtils.isInteger(httpServerPort) ? Integer.valueOf(httpServerPort) : 8080);
            DeploymentOptions options = new DeploymentOptions().setConfig(httpServerConfig).setInstances(2);
            vertx.deployVerticle("io.example.router.HttpServerVerticle", options, httpServerFuture);
            return httpServerFuture;
        }).setHandler(ar -> {
            if (ar.succeeded()) {
                startFuture.complete();
            } else {
                logger.error(ar.cause().getMessage());
                startFuture.fail(ar.cause());
            }
        });
    }
}
